package com.zhuchaooasystem.ui.home.service;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.presenter.home.servicemap.ServiceAddMapContract;
import com.zhuchaooasystem.presenter.home.servicemap.ServiceAddMapPresenter;
import com.zhuchaooasystem.utils.ScreenUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceAddMapActivity extends BaseActivity<ServiceAddMapPresenter> implements ServiceAddMapContract.View {

    @BindView(R.id.actionbar_relative_rootview)
    RelativeLayout relative_rootview;
    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    //----
    @BindView(R.id.act_service_add_map_mapview)
    MapView mapview;
    @BindView(R.id.act_service_add_map_txt_address)
    TextView txt_address;
    //----
    private BaiduMap baiduMap;
    private GeoCoder geo_coder = null; // 搜索模块，也可去掉地图模块独立使用
    private BitmapDescriptor bitmap_marker;
    private MyLocationConfiguration config;
    //----
    private String address;  //定位的地址

    @Override
    protected int getLayout() {
        return R.layout.activity_service_add_map;
    }

    @Override
    protected ServiceAddMapPresenter getPresenter() {
        return new ServiceAddMapPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getExtras()) {
            address = getIntent().getExtras().getString("address");
        }
        bitmap_marker = BitmapDescriptorFactory.fromResource(R.drawable.ic_location);
        baiduMap = mapview.getMap();
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, bitmap_marker);
    }

    @Override
    protected void initView() {
        setActionbar();
        //权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE}, Key.LOCATION);
        } else {
            setData();
        }
    }

    private void setData() {

        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setMyLocationConfigeration(config);
        //设置地图初始的缩放比例
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(20).build()));
        // 初始化搜索模块，注册事件监听
        geo_coder = GeoCoder.newInstance();
        geo_coder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                try {
                    if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                        ToastUtil.showShort(mContext, "抱歉，未能找到结果");
                        return;
                    }
                    baiduMap.clear();
                    baiduMap.addOverlay(new MarkerOptions().position(geoCodeResult.getLocation())
                            .icon(bitmap_marker));
                    baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(geoCodeResult.getLocation()));
                } catch (Exception e) {
                }
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            }
        });
        txt_address.setText(address);
        if (address.contains("市")) {
            geo_coder.geocode(new GeoCodeOption().city(address.substring(0, address.indexOf("市"))).address(address.substring(address.indexOf("市") + 1)));
        } else {
            geo_coder.geocode(new GeoCodeOption().address(address));
        }
    }

    private void setActionbar() {
        relative_rootview.setBackgroundColor(getResources().getColor(R.color.color_77000000));
        iv_back.setImageResource(R.drawable.ic_back_circle);
        iv_back.setPadding(ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10));
        iv_back.setVisibility(View.VISIBLE);
        txt_title.setTextColor(Color.WHITE);
        txt_title.setText(getString(R.string.actionbar_title_service_address_map));
    }

    @Override
    protected void initDataAndLoadData() {
    }

    @OnClick({R.id.actionbar_iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onPause();
        }
    }


    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.LOCATION:
                setData();
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }


}
